#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <sys/wait.h>
#include <sys/socket.h>
#include <json/json.h>

#define SEP " "
#define SEP_LEN strlen(SEP) // 不能使用sizeof()
#define LINE_SEP "\r\n"
#define LINE_SEP_LEN strlen(LINE_SEP) // 不能使用sizeof()

enum
{
    OK = 0,
    DIV_ZERO = 1,
    MOD_ZERO,
    OP_ERROR
};

// "x op y" -> "content_len"\r\n"x op y"
// "exitcode result" -> "content_len"\r\n"exitcode result"
std::string enLength(const std::string &text) // 添加报头
{
    std::string send_string = std::to_string(text.size());
    send_string += LINE_SEP;
    send_string += text;
    send_string += LINE_SEP;
    return send_string;
}
// "content_len"\r\n"x op y" -> "x op y"
bool deLength(const std::string &package, std::string *text) // 去除报头
{
    auto pos = package.find(LINE_SEP);
    if (pos == std::string::npos)
        return false;
    std::string text_len_string = package.substr(0, pos);
    int text_len = std::stoi(text_len_string);
    *text = package.substr(pos + LINE_SEP_LEN, text_len);
    return true;
}

class Request
{
public:
    Request() : x(0), y(0), op(0)
    {
    }
    Request(int x_, int y_, char op_) : x(x_), y(y_), op(op_)
    {
    }
    bool serialize(std::string *out) // 序列化
    {
#ifdef MYSELF
        std::string s;
        *out = "";
        std::string x_stirng = std::to_string(x);
        std::string y_stirng = std::to_string(y);

        *out += x_stirng;
        *out += SEP;
        *out += op;
        *out += SEP;
        *out += y_stirng;
#else
        Json::Value root;
        root["first"] = x;
        root["second"] = y;
        root["oper"] = op;

        Json::FastWriter writer;
        // Json::StyledWriter writer;
        *out = writer.write(root);
#endif
        return true;
    }
    // "x op y"
    bool deserialize(std::string &in)
    {
#ifdef MYSELF
        auto left = in.find(SEP);
        auto right = in.rfind(SEP);
        if (left == std::string::npos || right == std::string::npos)
            return false;
        if (left == right)
            return false;
        std::string x_string = in.substr(0, left);
        std::string y_string = in.substr(right + SEP_LEN);

        if (x_string.empty() || y_string.empty())
            return false;

        x = std::stoi(x_string);
        y = std::stoi(y_string);

        op = in[left + SEP_LEN];
#else
        Json::Value root;
        Json::Reader reader;
        reader.parse(in, root);

        x = root["first"].asInt();
        y = root["second"].asInt();
        op = root["oper"].asInt();
#endif
        return true;
    }
    // "x op y"
    int x;
    int y;
    char op;
};

class Response
{
public:
    Response() : exitcode(0), result(0)
    {
    }
    Response(int exitcode_, int result_) : exitcode(exitcode_), result(result_)
    {
    }
    bool serialize(std::string *out)
    {
#ifdef MYSELF
        *out = "";
        std::string ec_stirng = std::to_string(exitcode);
        std::string res_stirng = std::to_string(result);

        *out += ec_stirng;
        *out += SEP;
        *out += res_stirng;
#else
        Json::Value root;
        root["exitcode"] = exitcode;
        root["result"] = result;
        Json::FastWriter writer;
        *out = writer.write(root);
#endif
        return true;
    }
    bool deserialize(std::string &in)
    {
#ifdef MYSELF
        // exitcode result
        auto mid = in.find(SEP);
        if (mid == std::string::npos)
            return false;
        std::string ec_stirng = in.substr(0, mid);
        std::string res_stirng = in.substr(mid + SEP_LEN);
        if (ec_stirng.empty() || res_stirng.empty())
            return false;

        exitcode = std::stoi(ec_stirng);
        result = std::stoi(res_stirng);
#else
        Json::Value root;
        Json::Reader reader;
        reader.parse(in, root);

        exitcode = root["exitcode"].asInt();
        result = root["result"].asInt();
#endif
        return true;
    }
    int exitcode; // 0: 计算成功, !0表示计算失败, 定制标准
    int result;
};

bool recvPackage(int sock, std::string &inbuffer, std::string *text)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            inbuffer += buffer;
            // 分析
            auto pos = inbuffer.find(LINE_SEP);
            if (pos == std::string::npos)
                continue;
            std::string text_len_string = inbuffer.substr(0, pos);
            int text_len = std::stoi(text_len_string);
            int total_len = text_len_string.size() + 2 * LINE_SEP_LEN + text_len;
            if (inbuffer.size() < total_len)
                continue; // 如果不满足, 说明没有一个完整的报文

            std::cout << "处理前#inbuffer: \n" << inbuffer << std::endl;

            if (inbuffer.size() < total_len)
            {
                std::cout << "你输出的消息, 没有严格遵守我们的协议, 正在等待后续的内容" << std::endl;
            }

            // 至少有一个报文
            *text = inbuffer.substr(0, total_len);
            inbuffer.erase(0, total_len);

            std::cout << "处理后#inbuffer: \n"
                      << inbuffer << std::endl;
            break;
        }
        else
            return false;
    }
    return true;
}
// bool recvPackageAll(int sock, std::string &inbuffer, std::vector<std::string> *out)
// {
//     std::string line;
//     while(recvRequest(sock, inbuffer, &line)) out->push_back(line);
//     return true;
// }